using UnityEngine;

public class Shake : MonoBehaviour
{
    [SerializeField] private State state; //选择这个物体的shake状态

    [Header("GlobalSetting")]
    [SerializeField] private float shakeFrequency = 1f;  // 波动频率

    [Header("FixedFrequency")]
    [SerializeField] private float targetRotation = 10f; //目标旋转角度

    [Header("RandomFrequency")]
    //每次到目标旋转角度的时候，需要获取下次的最高旋转角度
    [SerializeField] private float targetRotationMin = 10f; //目标旋转角度最小

    [SerializeField] private float targetRotationMax = 20f; //目标旋转角度最大
    private float currentTargetRotation;
    private bool isChangeRotation;

    private float timer;

    public enum State
    {
        FixedFrequency,
        RandomFrequency
    }

    private void Start()
    {
        SetCurrentTargetRotation();
    }

    private void Update()
    {
        switch (state)
        {
            case State.FixedFrequency:
                timer += Time.deltaTime * shakeFrequency;
                transform.rotation = Quaternion.Euler(0f, 0f, targetRotation * Mathf.Sin(timer * shakeFrequency));
                break;

            case State.RandomFrequency:
                if (timer >= 0 && timer < 1)
                {
                    timer += Time.deltaTime * shakeFrequency;
                    transform.rotation = Quaternion.Euler(0f, 0f, currentTargetRotation * Mathf.Lerp(0, 1, timer));
                    if (timer > 1)
                    {
                        //SetCurrentTargetRotation();
                    }
                }
                if (timer >= 1 && timer < 2)
                {
                    timer += Time.deltaTime * shakeFrequency;
                    transform.rotation = Quaternion.Euler(0f, 0f, currentTargetRotation * Mathf.Lerp(1, 0, timer - 1));
                    if (timer > 2)
                    {
                        SetCurrentTargetRotation();
                    }
                }
                if (timer >= 2 && timer < 3)
                {
                    timer += Time.deltaTime * shakeFrequency;
                    transform.rotation = Quaternion.Euler(0f, 0f, currentTargetRotation * Mathf.Lerp(0, -1, timer - 2));
                    if (timer > 3)
                    {
                        //SetCurrentTargetRotation();
                    }
                }
                if (timer >= 3 && timer < 4)
                {
                    timer += Time.deltaTime * shakeFrequency;
                    transform.rotation = Quaternion.Euler(0f, 0f, currentTargetRotation * Mathf.Lerp(-1, 0, timer - 3));
                    if (timer > 4)
                    {
                        SetCurrentTargetRotation();
                    }
                }
                if (timer >= 4)
                {
                    timer = 0;
                }
                break;
        }
    }

    private void SetCurrentTargetRotation()
    {
        currentTargetRotation = Random.Range(targetRotationMin, targetRotationMax);
    }
}